package com.oasys.service.impl;

import com.oasys.dao.ApprovalMapper;
import com.oasys.entity.EmployPo;
import com.oasys.entity.LoginUser;
import com.oasys.entity.dto.AllApplyInfoDto;
import com.oasys.entity.dto.ApplyDto;
import com.oasys.entity.dto.SubmitApplyDto;
import com.oasys.entity.po.ApplyPo;
import com.oasys.entity.po.ApplyTypePo;
import com.oasys.entity.po.SubmitPo;
import com.oasys.entity.po.SubmitTypePo;
import com.oasys.entity.vo.LeaveApplyVo;
import com.oasys.entity.vo.QuitVo;
import com.oasys.entity.vo.SubmitVo;
import com.oasys.enums.OaResponseCode;
import com.oasys.service.ApprovalService;
import com.oasys.service.EmployService;
import com.oasys.service.RoleService;
import com.oasys.service.SysUserService;
import com.oasys.utils.AutoGenerateIds;
import com.oasys.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2022/5/17
 **/
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class ApprovalServiceImpl implements ApprovalService {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private ApprovalMapper approvalMapper;
    @Resource
    private EmployService employService;
    @Resource
    private RoleService roleService;

    @Value("${imgFilePath}")
    private String imgFilePath;

    /**
     * 离职数据查询
     * @return
     */
    @Override
    public List<ApplyDto> findResignApplyList() {
        try {
            LoginUser loginUser = sysUserService.getLoginUser();
            List<ApplyDto> quitList = approvalMapper.findResignApplyList(loginUser.getUserId());
            if (ObjectUtils.isNotEmpty(quitList)){
                for (ApplyDto dto : quitList) {
                    //查询审批人信息
                    EmployPo approvalApply = employService.findEmployInfoByUserId(dto.getApprovalUserId());
                    log.info("审批人信息:{}",approvalApply);
                    dto.setApplyName(loginUser.getUserName());
                    if (ObjectUtils.isNotEmpty(approvalApply)){
                        dto.setApprovalName(null == approvalApply.getStaffName() ? "":approvalApply.getStaffName());
                    }
                    findApplyTypeAndState(dto);
                }
            }
            return quitList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取申请类型、状态
     * @param applyDto
     */
    public void findApplyTypeAndState(ApplyDto applyDto){
        applyDto.setApplyType(approvalMapper.findApplyType(applyDto.getTypeId()));
        applyDto.setState(approvalMapper.findApplyState(applyDto.getStateId()));
    }

    /**
     * 请假数据查询
     * @return
     */
    @Override
    public List<ApplyDto> findLeaveApplyList() {
        try {
            LoginUser loginUser = sysUserService.getLoginUser();
            List<ApplyDto> leaveList = approvalMapper.findLeaveApplyList(loginUser.getUserId());
            if (ObjectUtils.isNotEmpty(leaveList)){
                for (ApplyDto dto : leaveList) {
                    //查询审批人信息
                    EmployPo approvalApply = employService.findEmployInfoByUserId(dto.getApprovalUserId());
                    dto.setApplyName(loginUser.getUserName());
                    dto.setApprovalName(approvalApply.getStaffName());
                    findApplyTypeAndState(dto);
                }
            }
            return leaveList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取请假类型数据
     * @return
     */
    @Override
    public ResponseResult<List<ApplyTypePo>> findApplyTypeAll() {
        ResponseResult<Object> result = new ResponseResult<>();
        List<ApplyTypePo> applyTypeAll = approvalMapper.findApplyTypeAll();
        result.setCode(OaResponseCode.SUCCESS.getCode());
        if (ObjectUtils.isNotEmpty(applyTypeAll)){
            return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,applyTypeAll);
        }
        return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null, Collections.singletonList(null));
    }


    /**
     * 请假申请
     * @param leaveApplyVo
     * @return
     */
    @Override
    public ResponseResult<Boolean> leaveApply(LeaveApplyVo leaveApplyVo) {
        try {
            LoginUser loginUser = sysUserService.getLoginUser();
            ApplyPo applyPo = new ApplyPo();
            applyPo.setApplyId(AutoGenerateIds.getGenerateId());
            applyPo.setApplyTitle(leaveApplyVo.getApplyTitle());
            applyPo.setTypeId(leaveApplyVo.getTypeId());
            applyPo.setApplyDetail(leaveApplyVo.getApplyDetail());
            applyPo.setApplyDate(new Date());
            applyPo.setApplyUserId(loginUser.getUserId());
            applyPo.setStateId(1L);
            //应该使用每个角色对应的固定编码
            Integer roleNo = roleService.getRoleNo(loginUser.getUserId());
            if (roleNo == 1){
                //经理申请
                applyPo.setApprovalUserId(1001L);
            } else if (roleNo == 88) {
                //主管
                applyPo.setApprovalUserId(1001L);
            } else if (roleNo == 66) {
                //普通员工
                applyPo.setApprovalUserId(985909793581432832L);
            }
            applyPo.setBeginDate(leaveApplyVo.getBeginDate());
            applyPo.setEndDate(leaveApplyVo.getEndDate());
            applyPo.setRejectMemo("");
            Boolean result = approvalMapper.saveLeaveApply(applyPo);
            return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,result);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseResult<>(OaResponseCode.FAIL.getCode(),null,false);
    }

    /**
     * 离职申请
     * @param quitVo
     * @return
     */
    @Override
    public ResponseResult<Boolean> resignApply(QuitVo quitVo) {
        try {
            LoginUser loginUser = sysUserService.getLoginUser();
            ApplyPo applyPo = new ApplyPo();
            applyPo.setApplyId(AutoGenerateIds.getGenerateId());
            applyPo.setApplyTitle(quitVo.getApplyTitle());
            applyPo.setTypeId(-1L);
            applyPo.setApplyDetail(quitVo.getApplyDetail());
            applyPo.setApplyDate(new Date());
            applyPo.setApplyUserId(loginUser.getUserId());
            applyPo.setStateId(1L);
            Integer roleNo = roleService.getRoleNo(loginUser.getUserId());
            if (roleNo == 1){
                //经理申请
                applyPo.setApprovalUserId(1001L);
            } else if (roleNo == 88) {
                //主管
                applyPo.setApprovalUserId(1001L);
            } else if (roleNo == 66) {
                //普通员工
                applyPo.setApprovalUserId(985909793581432832L);
            }
            applyPo.setBeginDate(new Date());
            applyPo.setEndDate(quitVo.getEndDate());
            applyPo.setRejectMemo("");
            Boolean result = approvalMapper.saveLeaveApply(applyPo);
            return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,result);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseResult<>(OaResponseCode.FAIL.getCode(),null,false);
    }

    /**
     * getSubmitType
     * @return list
     */
    @Override
    public ResponseResult<List<SubmitTypePo>> getSubmitType() {
        try {
            List<SubmitTypePo> submitType = approvalMapper.getSubmitType(null);
            return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,submitType);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,Collections.singletonList(null));
    }

    /**
     * 报销申请
     * @param submitVo vo
     * @return boolean
     */
    @Override
    public ResponseResult<Boolean> expenseApply(SubmitVo submitVo) {
        try {
            LoginUser loginUser = sysUserService.getLoginUser();
            String name = "";
            //文件上传
            if (ObjectUtils.isNotEmpty(submitVo.getSubmitImg())){
                String suffix = Objects.requireNonNull(submitVo.getSubmitImg().getOriginalFilename()).substring(submitVo.getSubmitImg().getOriginalFilename().lastIndexOf("."));
                name = System.currentTimeMillis()+submitVo.getSubmitImg().getName() + suffix;
                log.info("服务器地址:{},凭证名:{}",imgFilePath,name);
                File fileDir = new File(imgFilePath);
                if (!fileDir.exists()){
                    fileDir.mkdirs();
                }
                submitVo.getSubmitImg().transferTo(new File(fileDir,name));
            }
            SubmitPo submitPo = new SubmitPo();
            submitPo.setSubmitId(AutoGenerateIds.getGenerateId());
            submitPo.setSubmitTitle(submitVo.getSubmitTitle());
            submitPo.setTypeId(submitVo.getTypeId());
            submitPo.setSubmitDetail(submitVo.getSubmitDetail());
            submitPo.setSubmitMoney(submitVo.getSubmitMoney());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(submitVo.getSubmitDate());
            submitPo.setSubmitDate(date);
            submitPo.setApplyUserId(loginUser.getUserId());
            submitPo.setSubmitImg(name);
            //待审批
            submitPo.setStateId(1L);
            Integer roleNo = roleService.getRoleNo(loginUser.getUserId());
            if (roleNo == 1){
                //普工
                submitPo.setApprovalUserId(1001L);
            } else if (roleNo == 88) {
                //主管
                submitPo.setApprovalUserId(1001L);
            } else if (roleNo == 66) {
                //经理申请
                submitPo.setApprovalUserId(985909793581432832L);
            }
            Boolean bool = approvalMapper.saveExpenseApply(submitPo);
            return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,bool);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,false);
    }

    /**
     * 获取报销数据
     * @return
     */
    @Override
    public ResponseResult<List<SubmitApplyDto>> findExpenseApplyList() {
        try {
            LoginUser loginUser = sysUserService.getLoginUser();
            List<SubmitPo> list = approvalMapper.findExpenseApplyList(loginUser.getUserId());
            log.info("list:{}",list);
            List<SubmitApplyDto> submitApplyDtos = new ArrayList<>(8);
            //组装数据
            if (ObjectUtils.isNotEmpty(list)){
                for (SubmitPo submitPo : list) {
                    SubmitApplyDto submitApplyDto = new SubmitApplyDto();
                    submitApplyDto.setSubmitId(submitPo.getSubmitId());
                    submitApplyDto.setSubmitTitle(submitPo.getSubmitTitle());
                    submitApplyDto.setTypeId(submitPo.getTypeId());
                    submitApplyDto.setApplyType(approvalMapper.getSubmitType(submitApplyDto.getTypeId()).get(0).getTypeName());
                    submitApplyDto.setSubmitDetail(submitPo.getSubmitDetail());
                    submitApplyDto.setSubmitImg(submitPo.getSubmitImg());
                    submitApplyDto.setSubmitMoney(submitPo.getSubmitMoney());
                    submitApplyDto.setSubmitDate(submitPo.getSubmitDate());
                    submitApplyDto.setStateId(submitPo.getStateId());
                    submitApplyDto.setState(approvalMapper.findApplyState(submitApplyDto.getStateId()));
                    submitApplyDto.setApplyUserId(submitPo.getApplyUserId());
                    submitApplyDto.setApplyName(sysUserService.getStaffName(submitPo.getApplyUserId()));
                    submitApplyDto.setApprovalUserId(submitPo.getApprovalUserId());
                    submitApplyDto.setApprovalName(sysUserService.getStaffName(submitPo.getApprovalUserId()));
                    submitApplyDtos.add(submitApplyDto);
                }
            }
            return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,submitApplyDtos);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,Collections.singletonList(null));
    }

    /**
     * 获取所有申请信息
     * @return
     */
    @Override
    public ResponseResult<List<AllApplyInfoDto>> getApplyAllInfo() {
        try {
            LoginUser loginUser = sysUserService.getLoginUser();
            List<AllApplyInfoDto> list = new ArrayList<>();
            //获取离职/请假数据
            List<ApplyDto> applyDtos = approvalMapper.findAllApplyData(loginUser.getUserId());
            if (ObjectUtils.isNotEmpty(applyDtos)){
                for (ApplyDto dto : applyDtos) {
                    AllApplyInfoDto allApplyInfoDto = new AllApplyInfoDto();
                    //查询人员信息
                    EmployPo employApply = employService.findEmployInfoByUserId(dto.getApplyUserId());
                    allApplyInfoDto.setApplyId(dto.getApplyId());
                    allApplyInfoDto.setStaffName(employApply.getStaffName());
                    allApplyInfoDto.setStaffSex(employApply.getStaffSex());
                    allApplyInfoDto.setStaffTel(employApply.getStaffTel());
                    allApplyInfoDto.setStaffAge(employApply.getStaffAge());
                    allApplyInfoDto.setApplyTitle(dto.getApplyTitle());
                    allApplyInfoDto.setApplyDetail(dto.getApplyDetail());
                    findApplyTypeAndState(dto);
                    allApplyInfoDto.setApplyType(dto.getApplyType());
                    allApplyInfoDto.setStateId(dto.getStateId());
                    allApplyInfoDto.setApplyState(dto.getState());
                    allApplyInfoDto.setApplyTime(dto.getBeginDate());
                    list.add(allApplyInfoDto);
                }
            }
            //获取报销数据
            List<SubmitPo> allSubmitData = approvalMapper.findAllSubmitData(loginUser.getUserId());
            if (ObjectUtils.isNotEmpty(allSubmitData)){
                for (SubmitPo po : allSubmitData) {
                    AllApplyInfoDto allApplyInfoDto = new AllApplyInfoDto();
                    //查询人员信息
                    EmployPo employApply = employService.findEmployInfoByUserId(po.getApplyUserId());
                    allApplyInfoDto.setApplyId(po.getSubmitId());
                    allApplyInfoDto.setStaffName(employApply.getStaffName());
                    allApplyInfoDto.setStaffSex(employApply.getStaffSex());
                    allApplyInfoDto.setStaffTel(employApply.getStaffTel());
                    allApplyInfoDto.setStaffAge(employApply.getStaffAge());
                    allApplyInfoDto.setApplyTitle(po.getSubmitTitle());
                    allApplyInfoDto.setApplyDetail(po.getSubmitDetail());
                    allApplyInfoDto.setApplyType(approvalMapper.getSubmitType(po.getTypeId()).get(0).getTypeName());
                    allApplyInfoDto.setStateId(po.getStateId());
                    allApplyInfoDto.setApplyState(approvalMapper.findApplyState(po.getStateId()));
                    allApplyInfoDto.setApplyTime(po.getSubmitDate());
                    list.add(allApplyInfoDto);
                }
            }
            return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,list);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseResult<>(OaResponseCode.SUCCESS.getCode(),null,Collections.singletonList(null));
    }

    /**
     * 同意申请
     * @param applyId
     * @return
     */
    @Override
    public Boolean agreeApply(Long applyId) {
        try {
            //修改请假、离职状态
            Long applyInfo = approvalMapper.getApplyInfo(applyId);
            if (ObjectUtils.isNotEmpty(applyInfo)){
                return approvalMapper.updateApplyState(applyId,2L,"无");
            }
            //不在oa_apply中,就在oa_submit_apply中
            return approvalMapper.updateSubmitState(applyId,2L);
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 驳回申请
     * @param applyId
     * @param rejectMemo
     * @return
     */
    @Override
    public Boolean rejectApply(Long applyId,String rejectMemo) {
        try {
            //修改请假、离职状态
            Long applyInfo = approvalMapper.getApplyInfo(applyId);
            if (ObjectUtils.isNotEmpty(applyInfo)){
                return approvalMapper.updateApplyState(applyId,3L,rejectMemo);
            }
            //不在oa_apply中,就在oa_submit_apply中
            return approvalMapper.updateSubmitState(applyId,3L);
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
